package com.example.test003.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.test003.domain.ResponseResult;
import com.example.test003.domain.entity.SysUser;
import com.example.test003.pojo.VideoToken;
import com.example.test003.pojo.VideoTokenCity;
import com.example.test003.service.VideoTokenCityService;
import com.example.test003.service.VideoTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@RestController
public class VedioTokenController {
    @Autowired
    private VideoTokenService videoTokenService;
    @Autowired
    private VideoTokenCityService videoTokenCityService;

    @GetMapping("/getVedioToken")
    public String  getToken(String type,String location) {
        if ("2".equals(type)){
            System.out.println("ok");
            return "没有权限看摄像头";
        }
        if ("大方站".equals(location)){
            location="南京信息工程大学站";
        }

        String cityname =location;
        VideoTokenCity videoTokenCity=videoTokenCityService.getAppkeyAndSecret(cityname);//从数据库中请求appkey和secret

        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyyMMdd");
        String nowtime=currentDate.format(formatter);//拿到今天的日期
        System.out.println(nowtime);


        String tokenByURL=getTokenByURL(videoTokenCity.getAppkey(),videoTokenCity.getSecret());//得到最新的token
        LocalDate futureDate = currentDate.plusDays(7);
        String endtime = futureDate.format(formatter);//确定新token过期时间（7天后）
        System.out.println(endtime);

        //在插入新数据之前，要判断待插入的数据在库中是否存在
        VideoToken token1=videoTokenService.getTimeBytoken(tokenByURL,cityname);
        if (token1==null){
            videoTokenService.insertVideoToken(tokenByURL,endtime,cityname);
            System.out.println(tokenByURL);
            return tokenByURL;
        }else if (Integer.valueOf(token1.getEndtime())<=Integer.valueOf(nowtime)+1){
            videoTokenService.insertVideoToken(tokenByURL,endtime,cityname);
            System.out.println(tokenByURL);
            return tokenByURL;
        }else {
            return tokenByURL;

        }
    }

    public String getTokenByURL(String appkey,String secret){
        long current_timestamp = System.currentTimeMillis();
        Map<String, Object> pGS = new HashMap<>();
        pGS.put("m_nTokenExpireTime", 0L);
        pGS.put("m_strAppKey", "70590bcbc2bb468f8fa4640a238efc82");
        pGS.put("m_strSecret", "80a2b1785c2d6a380720bc00baeac522");
        pGS.put("m_strToken", "0");

        long expire_timestamp = (Long) pGS.get("m_nTokenExpireTime");

        String new_token=null;
        if (expire_timestamp <= current_timestamp) {
            try {
                String url = "https://open.ys7.com/api/lapp/token/get";
                URL apiUrl = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setDoOutput(true);

                Map<String, String> params = new HashMap<>();
                params.put("appKey", appkey);
                params.put("appSecret", secret);

                String postData = getPostDataString(params);
                byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
                conn.getOutputStream().write(postDataBytes);

                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder response = new StringBuilder();


                    String line;
                    JSONObject jsonObject = new JSONObject();
                    while ((line = br.readLine()) != null) {
                        if (line == null) {
                            break;
                        }
                        response.append(line);
                        jsonObject = JSON.parseObject(line);
                    }
                    new_token = jsonObject.getJSONObject("data").getString("accessToken");
                    br.close();
                    conn.disconnect();

                    pGS.put("m_nTokenExpireTime", current_timestamp + 7 * 24 * 60 * 60 * 1000);


                    System.out.println(new_token);
                } else {
                    System.out.println("Failed to retrieve AccessToken: " + conn.getResponseCode());
                }
            } catch (IOException e) {
                System.out.println("Failed to retrieve AccessToken: " + e.getMessage());
            }
        }
        return new_token;
    }
    private static String getPostDataString(Map<String, String> params) throws UnsupportedEncodingException, UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            result.append("&");
        }
        String postData = result.toString();
        return postData.length() > 0 ? postData.substring(0, postData.length() - 1) : postData;
    }
}
